import React from 'react';
import {View, ImageBackground, RefreshControl, ScrollView} from 'react-native';
import {useTranslation} from 'react-i18next';
import {useNavigation} from '@react-navigation/native';
import LineChart from '@/components/LineChart';
import {stationApi} from '@/services/api/stationApi';
import {useHeaderHeight} from '@react-navigation/elements';
import {Text, Button, useAppTheme, Card, Cell} from 'tsun-smart-ui';
import {useStatisticsPicker} from '@/hooks/usePicker';
import Network from '@/assets/icon/network-installer.svg';
import dayjs from 'dayjs';
import Logo from '@/components/Logo';
import {useQuery} from '@tanstack/react-query';
import {StatisticsOptions} from '@/enums/statistics';
import DeviceSkeleton from '@/components/DeviceList/DeviceSkeleton';

const Overview = () => {
  const {t} = useTranslation();
  const theme = useAppTheme();
  const navigation = useNavigation();
  const headerHeight = useHeaderHeight();
  const [Picker, timeUnitCode] = useStatisticsPicker();

  const {
    data: total,
    refetch,
    isFetching,
    isLoading,
    isSuccess,
    error,
  } = useQuery({
    queryKey: ['installer', 'scene', 'overview', timeUnitCode],
    queryFn: async () => {
      const {data} = await stationApi.getInstallerSceneOverview({
        grain: StatisticsOptions[timeUnitCode],
        year: dayjs().get('year'),
        month:
          timeUnitCode === 'sys.app.month' ? dayjs().get('month') + 1 : void 0,
      });
      return data;
    },
  });
  // 统计卡片数据

  if (isLoading) {
    return (
      <DeviceSkeleton className="px-4" style={{marginTop: headerHeight}} />
    );
  }
  if (error) throw new Error(error.message);

  if (isSuccess) {
    const statsCards = [
      {
        title:
          t('device.equipment') +
          t('device.totalNumber', {defaultValue: '总设备'}),
        count: total.deviceCount,
        color: theme.colors?.brand?.primary,
        iconProps: {
          backgroundColor: theme.colors?.brand?.primaryLight!,
          name: 'equipment',
        },
      },
      {
        title: t('job.status.Normal', {defaultValue: '正常设备'}),
        count: total.normalDeviceCount,
        color: theme.colors?.success?.primary,
        iconProps: {
          name: 'normal',
          backgroundColor: theme.colors?.success?.light!,
        },
      },
      {
        title: t('user.alarm', {defaultValue: '警告设备'}),
        count: total.faultDeviceCount,
        iconProps: {
          name: 'Alarm',
          backgroundColor: theme.colors?.error?.light!,
        },
        color: theme.colors?.error?.primary,
      },
      {
        title: t('monitor.tab.title.offline', {defaultValue: '离线设备'}),
        count: total.offlineDeviceCount,
        iconProps: {
          name: 'wifi',
          backgroundColor: theme.colors?.background?.disabled!,
        },
        color: theme.colors?.neutral?.primary,
      },
    ] as const;
    return (
      <ImageBackground
        imageStyle={{
          height: 402,
        }}
        source={!theme.isDark && require('@/assets/imgs/Background.png')}
        className="flex-1">
        <ScrollView
          style={{
            marginTop: headerHeight,
          }}
          refreshControl={
            <RefreshControl refreshing={isFetching} onRefresh={refetch} />
          }>
          <View className="p-4 flex-1">
            {/* 统计卡片区域 */}
            <View className="flex-row flex-wrap justify-between">
              {statsCards.map((card, index) => (
                <Card
                  className="mb-3"
                  key={index}
                  style={{
                    width: '48%',
                  }}>
                  <View className="flex-row flex-between">
                    <View className="flex-row gap-x-5 items-center">
                      <Logo
                        {...card.iconProps}
                        round={false}
                        size={24}
                        radius={8}
                        color={card.color!}
                        containerSize={36}></Logo>
                      <View>
                        <Text
                          className="font-heading"
                          style={{
                            color: card.color,
                            fontSize: 24,
                            lineHeight: 24,
                          }}>
                          {card.count}
                        </Text>
                        <Text
                          style={{
                            color: theme.colors?.neutral?.secondaryTitle,
                          }}>
                          {card.title}
                        </Text>
                      </View>
                    </View>
                  </View>
                </Card>
              ))}
            </View>

            {/* 趋势图表区域 */}
            <Card>
              <View className="flex-row flex-between">
                <Text variant="bodyMedium">
                  {t('workplace.totalInstalledCap')}
                </Text>
                <Button
                  onPress={() => {
                    Picker.show();
                  }}
                  size="small"
                  variant="text"
                  style={{
                    flexDirection: 'row-reverse',
                  }}
                  title={t(timeUnitCode)}
                  icon={'pull'}></Button>
              </View>
              <View className=" h-40">
                <LineChart
                  marker={`${t('sys.app.time')}: `}
                  chartData={[
                    total.installTrendList.map(item => item.installCount),
                  ]}
                  xAxisLabels={total.installTrendList.map(item => item.time)}
                  showLegend={false}
                  yAxis={{
                    left: {
                      drawAxisLine: false,
                    },
                  }}
                  scaleYEnabled={false}
                />
              </View>
            </Card>
            <Cell
              className=" mt-3"
              data={[
                {
                  title: t('common.networkTool', {
                    defaultValue: '配网工具',
                  }),
                  left: size => (
                    <Network
                      width={size}
                      height={size}
                      color={theme.colors?.brand?.primary}></Network>
                  ),
                  onPress: () => {
                    navigation.navigate('Scan', {
                      setupNetworkOnly: true,
                    });
                  },
                },
              ]}></Cell>
          </View>
        </ScrollView>
      </ImageBackground>
    );
  }
};

export default Overview;
